import { ScrollView } from "@tarojs/components";
import { request, showToast, showLoading, hideLoading } from "@tarojs/taro";
import { styled } from "linaria/lib/react";
import React, { FC, ReactElement, useEffect, useState } from "react";
import Pagination from "../../components/Pagination";
import { Blog } from "../../api/types";
import BlogCard from "../../components/BlogCard";
import ScrollToTop from "../../components/ScrollToTop";

interface IProps {}

const BlogList: FC<IProps> = (): ReactElement => {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    showLoading();
    request({
      url: "https://api.hongbin.xyz:3002/getBlogs",
      data: {
        verify: false,
        limit: 10,
        skip: (currentPage - 1) * 10,
        find: {
          status: "公开"
        },
        sort: {
          createAt: -1
        }
      },
      method: "GET",
      header: {
        "content-type": "application/json"
      },
      success: function({ data }) {
        console.log(data);
        setBlogs(data.blogs);
        setTotal(data.counts);
        hideLoading();
      },
      fail: function() {
        showToast({ title: "请求失败", icon: "error", duration: 2000 });
      }
    });
  }, [currentPage]);

  return (
    <Container scrollY>
      {blogs.map(blog => (
        <BlogCard key={blog._id} blog={blog} />
      ))}
      {total ? (
        <Pagination
          total={total}
          pageCount={10}
          currentPage={currentPage}
          onChange={setCurrentPage}
        />
      ) : null}
      {total ? <ScrollToTop /> : null}
    </Container>
  );
};

export default BlogList;

const Container = styled(ScrollView)`
  position: relative;
  height: 100%;
`;
